<template>
  <el-dialog v-model="showAddress" width="780" :title="or==0?'添加地址':'修改地址'"
             :close-on-click-modal="closeAddress">
    <div class="mask">
      <div class="check-address" v-if="or==2">
        <div class="check-address-content">
          <div class="check-address-content-item" v-for="(item,index) in addressArr" :key="item.id"
               @click="getAddressItem(item)">
            <p>收获人: {{ item.receiver }}</p>
            <p>联系方式: {{ item.contact }}</p>
            <p>收货地址: {{ item.fullLocation }}</p>
          </div>
        </div>
      </div>
      <el-form
          ref="ruleFormRef"
          style="max-width: 320px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
          v-else
      >
        <el-form-item label="收货人" prop="name">
          <el-input v-model="ruleForm.name"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"/>
        </el-form-item>
        <el-form-item label="地区" prop="address">

          <el-tree-select
              :model-value="ruleForm.address"
              :data="addressData"
              :props="defaultProps"
              node-key="code"
              :render-after-expand="false"
              style="width: 240px"
              @current-change="addressChange"
              :accordion="true"
              placeholder="请选择地址"
          />

        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="ruleForm.detailedAddress" style="width: 320px"/>
        </el-form-item>
        <el-form-item label="邮政编码" prop="postcode">
          <el-input v-model="ruleForm.postcode"/>
        </el-form-item>
        <el-form-item label="地址标签" prop="addressTag">
          <el-input v-model="ruleForm.addressTag"/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <span class="confirm-btn">取消</span>
        <span class="reset-btn" @click="submitForm(ruleFormRef)">确定</span>
      </div>
    </div>
  </el-dialog>

</template>

<script lang="ts" setup>
import {reactive, ref, onMounted, watchEffect} from 'vue'
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
import {getAddressApi} from '@/api/details/index'
import {ElMessage} from 'element-plus'
import mitt from "@/utils/mitt/index";
//蒙层控制
let showAddress = ref(false)
//点击其他地方控制蒙层
let closeAddress = ref(false)
//获取编辑地址数据
let emitAddress = ref({})
//控制是添加还是修改
let or = ref(null)

interface RuleForm {
  name: string
  phone: string
  address: string
  detailedAddress: string
  postcode: string
  addressTag: string
}


const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
//表单数据
let ruleForm = reactive<RuleForm>({
  name: emitAddress.value.receiver,
  phone: emitAddress.value.contact,
  address: emitAddress.value.fullLocation,
  detailedAddress: emitAddress.value.address,
  postcode: emitAddress.value.postalCode,
  addressTag: emitAddress.value.addressTags,
})


watchEffect(() => {
  ruleForm = reactive<RuleForm>({
    name: or.value == 1 ? emitAddress.value.receiver : '',
    phone: or.value == 1 ? emitAddress.value.contact : '',
    address: or.value == 1 ? emitAddress.value.fullLocation : '',
    detailedAddress: or.value == 1 ? emitAddress.value.address : '',
    postcode: or.value == 1 ? emitAddress.value.postalCode : '',
    addressTag: or.value == 1 ? emitAddress.value.addressTags : '',
  })
})


//修改数控组件的属性名 与 地址数据名相同
let defaultProps = {
  children: 'areaList', // 指定子节点的属性名
  label: 'name', // 指定节点标签的属性名
  value: 'code'   // 指定节点值的属性名
}

//获取地址Api
const addressData = ref({})

//获取地址数据
async function getAddress() {
  let res = await getAddressApi()
  addressData.value = res
}

//省数据
const provinceData = ref([])
//市数据及区数据
const detailAddressCode = ref([])
//海拔
const level = ref('')
//切换地址数组数据
let addressArr = ref([])

//地址改变
function addressChange(value, obj) {

  if (obj.parent.data.name) {
    //祖父
    let grandFatherAddress = obj.parent.parent.data.name ? obj.parent.parent.data.name : ''
    provinceData.value = obj.parent.parent.data.code ? obj.parent.parent.data.code : ''
    //这是父亲的
    let fatherAddress = obj.parent.data.name
    //这是当前的
    let nowAddress = obj.data.name
    detailAddressCode.value = obj.data.code
    level.value = obj.data.level
    ruleForm.address = `${grandFatherAddress} ${fatherAddress} ${nowAddress}`
  }
}


//表单校验规则
const rules = reactive<FormRules<RuleForm>>({
  name: [
    {required: true, message: '请输入收货人姓名', trigger: 'blur'},
    {min: 1, max: 5, message: '长度在 1 到 10 个字符', trigger: 'blur'},
  ],
  phone: [
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入手机号'));
        } else if (!/^1[3-9]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的手机号'));
        } else {
          callback();
        }
      },
      trigger: 'blur' // 可以在输入失去焦点时触发验证
    }

  ],
  address: [
    {required: true, message: '请输入地址', trigger: 'blur'},
    {min: 8, max: 20, message: '长度在 1到 20 个字符', trigger: 'blur'},
  ],
  detailedAddress: [
    {required: true, message: '请输入详细地址', trigger: 'blur'},
    {min: 10, max: 20, message: '长度在 10 到 20 个字符', trigger: 'blur'},
  ],
  postcode: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入邮政编码'));
        } else if (!/^\d{6}$/.test(value)) {
          ElMessage.error('请输入正确的邮政编码');
        } else {
          callback();
        }
      },
      trigger: 'blur' // 可选，表示在失去焦点时触发验证
    }
  ],
  addressTag: [
    {required: true, message: '请输入地址标签', trigger: 'blur'},
    {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'},
  ]
})

//表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (or.value == 0) {
        //新增地址
        let addAddressObj = ref({
          id: null, //新增地址为null 修改地址者有id
          address: ruleForm.detailedAddress,
          addressTags: ruleForm.addressTag,
          cityCode: detailAddressCode.value,
          contact: ruleForm.phone,
          countyCode: '110101',
          fullLocation: ruleForm.address,
          isDefault: 1,
          postalCode: ruleForm.postcode,
          provinceCode: provinceData.value,
          receiver: ruleForm.name,
        })
        showAddress.value = false
        emit('sendCloseAddMask', {showAddress: showAddress.value, addAddressObj: addAddressObj.value})
      } else if (or.value == 1) {
        let emitAddressObj = ref({
          id: emitAddress.value.id, //获取修改地址的id
          address: ruleForm.detailedAddress,
          addressTags: ruleForm.addressTag,
          cityCode: detailAddressCode.value.length > 0 ? detailAddressCode.value : emitAddress.value.cityCode,
          contact: ruleForm.phone,
          countyCode: '110101',
          fullLocation: ruleForm.address,
          isDefault: 1,
          postalCode: ruleForm.postcode,
          provinceCode: provinceData.value.length > 0 ? provinceData.value : emitAddress.value.provinceCode,
          receiver: ruleForm.name,
        })
        showAddress.value = false
        emit('sendCloseEmitMask', {showAddress: showAddress.value, emitAddressObj: emitAddressObj.value})
      }


    } else {
      console.log('error submit!', fields)
    }
  })
}


//获取切换地址数据
function getAddressItem(item: object) {
  showAddress.value = false
  emit('sendChangeAddress', {showAddress: showAddress.value, changeAddressObj: item})
}


onMounted(() => {
  //监听点击添加的数据
  mitt.on('AddShowAddress', (data: object) => {
    showAddress.value = data.showAddress
    or.value = data.or
  })
  //监听点击编辑的数据
  mitt.on('emitShowAddress', (data: object) => {
    console.log(data)
    showAddress.value = data.showAddress
    or.value = data.or
    emitAddress.value = data.addressObj
  })
  //获取地址数组数据(切换)
  mitt.on('getAddressArr', (data: object) => {
    showAddress.value = data.showAddress
    or.value = data.or
    addressArr.value = data.addressArr
  })
  getAddress()
})
let emit = defineEmits(['sendColseMask'])
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}

.confirm-btn {
  display: inline-block;
  background-color: #ccc;
  width: 15rem;
  height: 4.16rem;
  color: #fff;
  border: none;
  border-radius: 0.32rem;
  font-size: 1.33rem;
  cursor: pointer;
  margin-right: 1.2rem;
  line-height: 4.16rem;
  text-align: center;
}

.reset-btn {
  display: inline-block;
  background-color: var(--primary-color);
  width: 15rem;
  height: 4.16rem;
  color: #fff;
  border: none;
  border-radius: 0.32rem;
  font-size: 1.33rem;
  cursor: pointer;
  line-height: 4.16rem;
  text-align: center;
}

.mask {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.check-address {
  width: 100%;
  margin-bottom: 2.5rem;
}

.check-address-content {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;

}

.check-address-content-item {
  width: 100%;
  border: 1px solid #ccc;
  padding: 1.14rem 0.833rem;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 0.43rem;
}

.check-address-content-item:hover {
  background-color: rgba(39, 186, 155, 0.1);
  border: 1px solid var(--primary-color);
  cursor: pointer;
}

.check-address-content-item p {
  font-size: 1rem;
  color: #333;
}


</style>
